using System;
using System.Collections.Generic;
using System.Text;
using Koda.VisualStudio.Integration;
using EnvDTE80;
using Koda.VisualStudio;
using Koda.Search;
using Koda.UI;
using System.Windows.Forms;
using Koda.Utils;
using Koda.Search.Finders;

namespace Koda.Commands
{
    public class GotoTestClassCommand : VsCommand
    {
        public GotoTestClassCommand()
            : base("Go to unit test class", "Code Window", 1)
        {
        }

        public override bool OnQueryStatus(VsCommandEventArgs e)
        {
            if (VsCodeModelUtilities.GetClassFromSelection(e.DTE) != null)
                return true;
            return false;
        }

        public override void OnExecute(VsCommandEventArgs e)
        {
            CodeClass2 codeClass = VsCodeModelUtilities.GetClassFromSelection(e.DTE);          

            if (codeClass != null)
            {
                IVsItemFinder finder = this.FindTestClass(e.DTE, codeClass.Name);
                if (finder == null)
                {
                    MessageBox.Show(String.Format("Couldn't find any test class for '{0}'", codeClass.Name));
                }
                else if (finder.Result.Count == 1)
                {
                    finder.OpenItem(finder.Result[0]);
                }
                else if (finder.Result.Count > 1)
                {
                    OpenForm form = new OpenForm(finder);
                    form.ShowDialog();
                }
            }
        }

        private IVsItemFinder FindTestClass(DTE2 dte, string className)
        {
            string[] testClassNames = new string[] 
            { 
                String.Format("{0}Test", className),
                String.Format("{0}Fixture", className)
            };

            IVsItemFinder finder = new TypeFinder(dte);

            foreach (string testClassName in testClassNames)
            {
                int hits = finder.Search(testClassName);
                if (hits > 0)
                {
                    return finder;
                }
            }

            return null;
        }
    }
}
